package com.mars.admin.modules.post.service.impl;

import com.mars.admin.modules.base.service.impl.BaseServiceImpl;
import com.mars.admin.modules.post.entity.Topic;
import com.mars.admin.modules.post.mapper.TopicMapper;
import com.mars.admin.modules.post.service.ITopicService;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 话题服务实现类
 *
 * @author Mars
 * @version 1.0
 * @date 2025-01-07
 */
@Slf4j
@Service
public class TopicServiceImpl extends BaseServiceImpl<Topic> implements ITopicService {

    @Autowired
    private TopicMapper topicMapper;

    @Override
    public List<Topic> getTopicsByCategory(String category) {
        return topicMapper.selectByCategory(category);
    }

    @Override
    public List<Topic> getHotTopics(Integer limit) {
        return topicMapper.selectHotTopics(limit);
    }

    @Override
    public List<Topic> getOfficialTopics() {
        return topicMapper.selectOfficialTopics();
    }

    @Override
    public List<Topic> searchTopics(String keyword) {
        return topicMapper.searchTopics(keyword);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateTopicStats(Long topicId, Integer postsCount, Integer followersCount) {
        try {
            int result = topicMapper.updateTopicStats(topicId, postsCount, followersCount);
            return result > 0;
        } catch (Exception e) {
            log.error("更新话题统计数据失败，话题ID：{}，帖子数增量：{}，关注数增量：{}", topicId, postsCount, followersCount, e);
            throw e;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createTopic(Topic topic) {
        try {
            // 设置默认值
            if (topic.getPostsCount() == null) {
                topic.setPostsCount(0);
            }
            if (topic.getFollowersCount() == null) {
                topic.setFollowersCount(0);
            }
            if (topic.getIsHot() == null) {
                topic.setIsHot(0);
            }
            if (topic.getIsOfficial() == null) {
                topic.setIsOfficial(0);
            }
            if (topic.getStatus() == null) {
                topic.setStatus(1);
            }
            if (topic.getSortOrder() == null) {
                topic.setSortOrder(0);
            }
            
            topic.setCreateTime(LocalDateTime.now());
            topic.setUpdateTime(LocalDateTime.now());
            
            return save(topic);
        } catch (Exception e) {
            log.error("创建话题失败，话题信息：{}", topic, e);
            throw e;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateTopic(Topic topic) {
        try {
            topic.setUpdateTime(LocalDateTime.now());
            return updateById(topic);
        } catch (Exception e) {
            log.error("更新话题失败，话题信息：{}", topic, e);
            throw e;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteTopic(Long topicId) {
        try {
            return removeById(topicId);
        } catch (Exception e) {
            log.error("删除话题失败，话题ID：{}", topicId, e);
            throw e;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean setTopicHot(Long topicId, Integer isHot) {
        try {
            Topic topic = new Topic();
            topic.setId(topicId);
            topic.setIsHot(isHot);
            topic.setUpdateTime(LocalDateTime.now());
            return updateById(topic);
        } catch (Exception e) {
            log.error("设置话题热门状态失败，话题ID：{}，热门状态：{}", topicId, isHot, e);
            throw e;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean setTopicOfficial(Long topicId, Integer isOfficial) {
        try {
            Topic topic = new Topic();
            topic.setId(topicId);
            topic.setIsOfficial(isOfficial);
            topic.setUpdateTime(LocalDateTime.now());
            return updateById(topic);
        } catch (Exception e) {
            log.error("设置话题官方状态失败，话题ID：{}，官方状态：{}", topicId, isOfficial, e);
            throw e;
        }
    }

    @Override
    public Page<Topic> pageTopics(Page<Topic> page, String name, String category, Integer isHot, Integer isOfficial, Integer status) {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .from("tb_topic")
                .where("is_deleted = 0");
        
        // 构建查询条件
        if (name != null && !name.trim().isEmpty()) {
            queryWrapper.and("name LIKE ?", "%" + name + "%");
        }
        
        if (category != null && !category.trim().isEmpty()) {
            queryWrapper.and("category = ?", category);
        }
        
        if (isHot != null) {
            queryWrapper.and("is_hot = ?", isHot);
        }
        
        if (isOfficial != null) {
            queryWrapper.and("is_official = ?", isOfficial);
        }
        
        if (status != null) {
            queryWrapper.and("status = ?", status);
        }
        
        // 按排序字段和创建时间排序
        queryWrapper.orderBy("sort_order ASC, create_time DESC");
        
        return page(page, queryWrapper);
    }
}